package com.cyzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyzy.dto.ScoreProductListDto;
import com.cyzy.mapper.OredrsMapper;
import com.cyzy.mapper.ScoreProductMapper;
import com.cyzy.pojo.Orders;
import com.cyzy.pojo.ScoreProduct;
import com.cyzy.service.ScoreProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ScoreProductServiceImpl implements ScoreProductService {

    @Autowired
    private ScoreProductMapper scoreProductMapper;
    
    @Autowired
    private OredrsMapper ordersMapper;

    @Override
    public List<ScoreProductListDto> getScoreProductList() {
        // 查询所有状态为1（启用）的积分商品
        QueryWrapper<ScoreProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("score_product_status", 1);
        List<ScoreProduct> scoreProducts = scoreProductMapper.selectList(queryWrapper);
        
        List<ScoreProductListDto> result = new ArrayList<>();
        
        for (ScoreProduct product : scoreProducts) {
            // 计算销量：统计订单表中的销售数量
            QueryWrapper<Orders> orderQuery = new QueryWrapper<>();
            orderQuery.eq("order_type", "积分")
                     .eq("related_id", product.getScoreProductId())
                     .in("order_status", 1, 2); // 已付款和待付款
            Long salesCount = ordersMapper.selectCount(orderQuery);
            
            // 计算库存（实际可用库存 = 总库存 - 已售数量）
            long availableStock = product.getScoreProductStock() - (salesCount != null ? salesCount : 0);
            
            // 构建DTO对象
            ScoreProductListDto dto = new ScoreProductListDto();
            dto.setId(product.getScoreProductId());
            dto.setName(product.getScoreProductName());
            dto.setScore(product.getScoreProductCostScore());
            dto.setPrice(product.getScoreProductPrice());
            dto.setStock(availableStock + product.getScoreProductUnit()); // 库存+单位
            dto.setSalesVolume((salesCount != null ? salesCount : 0) + product.getScoreProductUnit()); // 销量+单位
            dto.setProductInfo(product.getScoreProductInfo());
            dto.setProductImage(product.getScoreProductImg());
            
            result.add(dto);
        }
        
        return result;
    }
}
